<template>
	<view class="wxlogin">
		<view>
			<!-- <text>	{{$BASE_URL + '/st/mini/static/img/lika.png'}} </text> -->
		
			<!-- https://webapp.shenghua6.cn/st/mini/static/img/lika.png -->
			<image :src="$BASE_URL + '/st/mini/static/img/lika.png'" mode=""
				style="width: 190upx; height: 190upx; margin: 0 auto; display: flex;"></image>
			<view class="btn" @click="wxLoginShow = true">一键登录注册</view>
			<view class="btns" @click="fanhui()">取消登录</view>
		</view>

		<u-popup v-model="wxLoginShow" mode="bottom" style="background: none">
			<view class="wxPop">
				<ul>
					<li class="li">
						<!-- @click="wxGetUserInfo()" -->
						<button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
							微信一键登录
						</button>
					</li>
					<li class="li" @click="goPath" style="margin-bottom: 0">
						手机验证码登录
					</li>
					<li class="li" @click="wxLoginShow = false" style="margin-bottom: 121upx; background-image: none">
						取消
					</li>
				</ul>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import Vue from "vue";
	import SDK from "@/commons/NIM_Web_SDK_miniapp_v8.5.0.js";
	import {
		decrypt,
		CreateIM
	} from "@/commons/util.des.js";


	export default {

		data() {
			return {

				sex: 3,
				$BASE_URL: this.$BASE_URL,
				wxLoginShow: false,
				loginRes: "",
				encryptedData: "",
				iv: "",
			};
		},
		onLoad(e) {

			if (e.id == 1) {
				// console.log('登录失效重新登陆')
				uni.showToast({
					title: "登录失效重新登陆",
					icon: "none",
					duration: 2000,
				});


			}
		},
		onShow() {


			uni.login({
				provider: "weixin",
				success: (loginRes) => {
					console.log(loginRes);
					this.loginRes = loginRes.code;
				},
				fail: () => {
					uni.showToast({
						title: "获取 code 失败",
						icon: "none",
					});
				},
			});
		},
		mounted() {},
		methods: {

			goPath() {
				uni.navigateTo({
					url: "../login/login",
				});
			},
			apiThirdLogin() {

				var _this = this
				this.loginRes
				console.log(this.loginRes,'this.loginResthis.loginResthis.loginResthis.loginResthis.loginRes')


				var data = {
					url: "/web/v2/api/app/apiThirdLoginEx",
					methods: "post",
					data: {
						type: "wx",
						account: this.loginRes,
						// projectId: "xcxlika",
						appletsEncryptedData: this.encryptedData,
						appletsIv: this.iv,
						sex: this.sex
					},
				};

				this.$http(data).then((res) => {
					console.log(res, "登录的返回6666")
					
					if (res.data.code == 40001){
						
						uni.navigateTo({
							url: "../login/login",
						});
						
						
					}else if (res.data.code == 21000) {
						uni.setStorage({
							key: 'userInfo',
							data: res.data.data,
							success: function() {
								console.log('success');
							}
						});
						var cookie = res.header["Set-Cookie"];
						console.log(cookie, "cookie1")
						if (cookie) {
							wx.setStorageSync("cookie", res.header["Set-Cookie"]); //服务器返回的Set-Cookie，保存到本地
						}


						// 登录埋点
						// AuthorizedLoginResult 埋点名称
						// is_no_authorization	是否授权	BOOL	
						// login_method	登录方式	STRING	手机号/微信/
						console.log('登陆埋点', getApp().sensors)
						getApp().sensors.track('AuthorizedLoginResult', {

							login_method: '微信'

						})
						// 神策数据更新用户的绑定id  随机匿名id 改成  userid
						getApp().sensors.login(res.data.data.userId)
					




						CreateIM(res.data.data.userId, res.data.data.imPwd, res)
						return



						//  IM实例化


						var gllist = getApp().globalData
						Vue.prototype.$NIM = SDK.NIM.getInstance({

							debug: true,

							appKey: "7ca5cef23fd00cb4774107175ab6d413",
							account: res.data.data.userId,
							token: decrypt(res.data.data.imPwd),
							// im登陆成功
							onconnect: onConnect,

							onWillReconnect: onWillReconnect,

							// im 断开
							ondisconnect: onDisconnect,
							// 收到会话列表
							onsessions: onSessions,
							onupdatesession: onUpdateSession,
							// 消息接受
							onmsg: onMsg

						});



						function onSessions(sessions) {
							console.log('收到会话列表', sessions);
							// getApp().globalData.list= sessions

							gllist.sessions = _this.$NIM.mergeSessions(gllist.sessions, sessions);
							updateSessionsUI();
						}

						function onUpdateSession(session) {
							console.log('会话更新了', session);

							gllist.sessions = _this.$NIM.mergeSessions(gllist.sessions, session);
							updateSessionsUI(session);

						}

						function updateSessionsUI(session) {


							if (session) {
								var type = session.lastMsg.type
								 
								if (type == "custom") {
									console.log('会话更新暂不支持此类型消息')
									return
								}


								// 刷新界面
								gllist.sessions
								console.log('刷新页面')

								uni.$emit('update', {
									addrsssid: '更新操作',
								});
								// 更新聊天记录
								if (session) {
									uni.$emit('updateHH', {
										addrsssid: session,
									});

								}

							}

						}

						function onMsg(msg) {
							console.log('收到消息6666', msg.scene, msg.type, msg);
							// pushMsg(msg);
							switch (msg.type) {
								case 'custom':
									onCustomMsg(msg);
									break;
								case 'notification':
									// 处理群通知消息
									onTeamNotificationMsg(msg);
									break;
									// 其它case
								default:
									break;
							}
						}



						var nei = {
							appKey: "7ca5cef23fd00cb4774107175ab6d413",
							account: res.data.data.userId,
							token: decrypt(res.data.data.imPwd),
						}


						uni.setStorage({
							key: 'nei',
							data: nei,
							success: function() {
								console.log('success');
							}
						});

						// 是否首次登录

						uni.setStorage({
							key: 'shifoushouci',
							data: res.data.data.isThirdReg,
							success: function() {
								console.log('success');
							}
						});




						function onConnect() {
							console.log("登录页=========================IM连接成功");
						}

						function onWillReconnect(obj) {
							// 此时说明 SDK 已经断开连接, 请开发者在界面上提示用户连接已断开, 而且正在重新建立连接
							console.log('即将重连');
							console.log(obj.retryCount);
							console.log(obj.duration);

							uni.showToast({
								title: '正在连接...',
								icon: 'none',
								duration: 2000
							});


						}

						function onDisconnect(error) {
							// 此时说明 SDK 处于断开状态, 开发者此时应该根据错误码提示相应的错误信息, 并且跳转到登录页面
							console.log("丢失连接");

							uni.showToast({
								title: '连接丢失...',
								icon: 'none',
								duration: 2000
							});

							console.log(error);
							if (error) {
								switch (error.code) {
									// 账号或者密码错误, 请跳转到登录页面并提示错误
									case 302:
										break;
										// 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
									case 417:
										break;
										// 被踢, 请提示错误后跳转到登录页面
									case "kicked":
										console.log("kicked");

										if (error.reason == "samePlatformKick") {
											uni.showToast({
												title: "您的帐号在异地登陆",
												duration: 2000,
												icon: "none",
											});
											setTimeout(function() {
												//清除本地登录状态
												// uni.clearStorage();
												// 清除本地cookie
												uni.removeStorage({key: 'cookie'});
												//IM实例销毁
												Vue.prototype.$NIM.disconnect();

												//跳转登录页
												uni.redirectTo({
													url: "/pages/login/wxlogin",
												});
											}, 2000);
										}


										if (error.reason == "serverKick") {
											uni.showToast({
												title: "您的帐号已被封禁",
												duration: 2000,
												icon: "none",
											});
											setTimeout(function() {
												//清除本地登录状态
												// 清除本地cookie
												uni.removeStorage({key: 'cookie'});
												// uni.clearStorage();
												//IM实例销毁
												Vue.prototype.$NIM.disconnect();

												//跳转登录页
												uni.redirectTo({
													url: "/pages/login/wxlogin",
												});
											}, 2000);


										}
										break

									default:
										break;
								}
							}
						}
						// uni.setStorage({
						// 	key: "userInfo",
						// 	data: res.data.data,
						// 	success: function() {},
						// });
						// uni.setStorage({
						//   key: "sessionId",
						//   data: res.data.sessionId,
						//   success: function () {
						//     console.log("success");
						//   },
						// });

						uni.switchTab({
							url: "../index/index",
						});
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: "none",
							duration: 2000,
						});


						uni.login({
							provider: "weixin",
							success: (loginRes) => {
								console.log(loginRes);
								this.loginRes = loginRes.code;
							},
							fail: () => {
								uni.showToast({
									title: "获取 code 失败",
									icon: "none",
								});
							},
						});

					}
				});
			},
			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:ok") {
					this.encryptedData = e.detail.encryptedData;
					this.iv = e.detail.iv;
					this.apiThirdLogin();
				}
			},


			// 获取授权
			wxGetUserInfo(e) {
				// 推荐使用wx.getUserProfile获取用户信息，
				// 开发者每次通过该接口获取用户个人信息均需用户确认，
				// 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗			
				wx.getUserProfile({
					desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						console.log(res.userInfo," 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写")
						this.sex = res.userInfo.gender
					}
				})
			},

			fanhui: function() {
				uni.reLaunch({
					url: '/pages/index/index'
				})

			}
		},
	};
</script>


<style lang="scss" scoped>
	.wxlogin /deep/ .u-drawer-bottom {
		background: none;
	}

	.wxlogin {
		width: 100%;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 1111;
		background: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.btn {
		width: 460upx;
		height: 88upx;
		line-height: 88upx;
		background-image: linear-gradient(197deg, #5d66ff 0%, #c19dff 100%);
		box-shadow: inset 0 0 9upx 4upx rgba(230, 250, 255, 0.43);
		border-radius: 44upx;
		font-size: 32upx;
		font-weight: bold;
		text-align: center;
		color: #ffffff;
		margin: 0 auto;
		margin-top: 230upx;
	}

	.btns {
		width: 460upx;
		height: 88upx;
		line-height: 88upx;
		background-image: linear-gradient(197deg, #000 0%, #666 100%);
		box-shadow: inset 0 0 9upx 4upx rgba(230, 250, 255, 0.43);
		border-radius: 44upx;
		font-size: 32upx;
		font-weight: bold;
		text-align: center;
		color: #ffffff;
		margin: 0 auto;
		margin-top: 40upx;
	}


	.wxPop {
		font-size: 36upx;
		color: #ffffff;

		.li {
			margin: 0 auto;
			width: 504upx;
			height: 104upx;
			border-radius: 52upx;
			line-height: 104upx;
			text-align: center;
			margin-bottom: 26upx;
			background-image: linear-gradient(to right, #aea2ff, #7077ff);
		}
	}

	button::after {
		border: none;
		background: none;
	}

	button {
		border-radius: 52upx;
		height: 104upx;
		line-height: 104upx;
		background-image: linear-gradient(to right, #86d67f, #2cbd87);
		width: 100%;
		margin: 0 auto;
		padding: 0;
		font-size: 36upx;
		color: #ffffff;
		text-align: center;
	}

	.btn-hover {
		background-color: transparent;
	}
</style>
